#include "engine.h"
#include "rendermesh.h"
#include "rendersystem.h"
#include "rendermaterial.h"
#include <gl/glew.h>

void submesh_t::init(uint32 num_vertices, uint32 num_indices, rendermaterial_t* m)
{
	material=m;
//	shader=rendersystem_t::get_shader(shadername);
	vertexbuffer.init(num_vertices,material->vdecl);
	indexbuffer.init(num_indices);
}
void submesh_t::set()
{
	GLASSERT;
	vertexbuffer.set();
	GLASSERT;
	indexbuffer.set();
	GLASSERT;

	GLASSERT;
	material->set();
#ifdef LEO_DESIGNER
	if (RSYS->selection_on)
		RSYS->get_material("wireframe")->shader->set();
//	else
#endif
	GLASSERT;
	if (textures.size() && textures[0])
	{
		GLASSERT;
		glActiveTexture(GL_TEXTURE0);
//		glEnable(GL_TEXTURE_2D);
		GLASSERT;
		glBindTexture(GL_TEXTURE_2D, textures[0]->hwid);
		GLASSERT;

		if (textures.size()>1)
		{
			GLASSERT;
			glActiveTexture(GL_TEXTURE1);
//			glEnable(GL_TEXTURE_2D);
			GLASSERT;
			glBindTexture(GL_TEXTURE_2D, textures[1]->hwid);
		}
	}
	else
	{
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, RSYS->whitetextureid);
	}
}

void submesh_t::draw()
{
	GLASSERT;
	glDrawElements(GL_TRIANGLES,indexbuffer.numindices,GL_UNSIGNED_SHORT,0);
	GLASSERT;
}

#ifdef LEO_DESIGNER
void rendermesh_t::save(file_t& f)
{
	f.write(submesh.size());

	for (uint32 n=0; n<submesh.size(); ++n)
	{
		submesh[n].save(f);
	}
}

void submesh_t::save(file_t& f)
{
	//material
	f.write(material->name);

	//textures
	f.write(textures.size());

	for (uint32 n=0; n<textures.size(); ++n)
		f.write(textures[n]->name);

	//vb
	f.write(vertexbuffer.vertexnum);
	f.write(vertexbuffer.vertexsize);
	void* ptr=vertexbuffer.lock_read();
	f.write(ptr,vertexbuffer.vertexnum*vertexbuffer.vertexsize);
	vertexbuffer.unlock();

	//ib
	f.write(indexbuffer.numindices);
	ptr=indexbuffer.lock_read();
	f.write(ptr,indexbuffer.numindices*sizeof(uint16));
	indexbuffer.unlock();
}
#endif
void rendermesh_t::load(file_t& f)
{
	uint32 submeshnum;
	f.read(submeshnum);
	submesh.resize(submeshnum);

	for (uint32 n=0; n<submesh.size(); ++n)
	{
		submesh[n].load(f);
	}
}


void submesh_t::load(file_t& f)
{
	//material
	stringhash matname;
	f.read(matname);
	material=RSYS->get_material(matname);

	//textures
	uint32 textnum;
	f.read(textnum);

	textures.resize(textnum);
	for (uint32 n=0; n<textures.size(); ++n)
	{
		stringhash textname;
		f.read(textname);
		textures[n]=RSYS->get_texture(textname);
	}

	//vb
	uint32 vnum,vsize;
	f.read(vnum);
	f.read(vsize);
	vertexbuffer.init(vnum,material->vdecl);
	void* ptr=vertexbuffer.lock();
	f.read(ptr,vnum*vsize);
	vertexbuffer.unlock();

	//ib
	uint32 numindices;
	f.read(numindices);
	indexbuffer.init(numindices);
	ptr=indexbuffer.lock();
	f.read(ptr,indexbuffer.numindices*sizeof(uint16));
	indexbuffer.unlock();
}
